import { operationToColor } from "../utils/help";

// 多Y轴
let baseOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
        type: 'cross'
    }
  },
  dataZoom: [
    {
      xAxisIndex: [0],
      filterMode: 'filter'
    }
  ],
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: [
    {
      type: 'value'
    },
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: 'Union Ads',
      type: 'line',
      stack: 'Total',
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: 'Video Ads',
      type: 'line',
      stack: 'Total',
      data: [150, 232, 201, 154, 190, 330, 410]
    },
    {
      name: 'Direct',
      type: 'line',
      stack: 'Total',
      data: [320, 332, 301, 334, 390, 330, 320]
    },
    {
      name: 'Search Engine',
      type: 'line',
      stack: 'Total',
      data: [820, 932, 901, 934, 1290, 1330, 1320]
    }
  ]
};

function setLegend(legend) {
  baseOption.legend = legend;
}

function setLegendData(data) {
  baseOption.legend.data = data;
}

function setDates(data) {
  baseOption.xAxis.data = data;
}

function buildMarkAreaDate(dates) {
  let grouped = dates.reduce((map, item) => {
  let key = item.slice(0, 4);
  const group = map.get(key) || [];
  group.push(item);
  return map.set(key, group);
  }, new Map());

  let ret = []
  grouped.forEach((value, key) => {
    if(key % 2 === 0) {
        let item = [{
          name: key,
          xAxis: value[0],
        },
        {
          xAxis: value[value.length - 1],
        }]

      ret.push(item)
    }
  });
  return ret
}

function getMarkAreaDate(dates) {
  return {
    itemStyle: {
      color: 'rgba(255, 173, 177, 0.4)'
    },
    data: buildMarkAreaDate(dates)
  }
}

function getMarkPoint(data, opShow = true, sDate = '') {
  let ret = []

  data.forEach(element => {
    if (opShow && element.operation !== null) {
      element.operation.forEach(i => {
        if (["买入","卖出","分红","模拟买入", "模拟卖出"].includes(i.operation)) {
          ret.push({
            name: i.operation,
            value: i.operation,
            xAxis: element.date,
            yAxis: element.close,
            itemStyle: {
              color: operationToColor(i.operation)
            }
          })
        }
      });
    }

    if (sDate && sDate === element.date) {
      ret.push({
        name: element.date,
        value: "开始",
        xAxis: element.date,
        yAxis: element.close,
      })
    }
  });
  return ret
}

// 绘制 300 日线图
export function built300dEchatOption(data, opShow = true, lpShow = false, sDate = '') {
  setLegend({
    data: ["close", "15W", "20W", "30W", "60W", "level_point"],

    selected: {
      "close": true,
      "15W": false,
      "20W": true,
      "30W": true,
      "60W": true,
      "level_point": lpShow
    }
  });

  let dates = []
  let closes = []
  let mean75dCloses = []
  let mean20WCloses = []
  let mean30WCloses = []
  let meanCloses = []
  let levelPoints = []

  data.forEach(element => {
    dates.push(element.date);
    closes.push(element.close);
    mean75dCloses.push(element.mean75Close);
    mean20WCloses.push(element.mean20WClose);
    mean30WCloses.push(element.mean30WClose);
    meanCloses.push(element.mean300Close);
    levelPoints.push(element.lp);
  });

  setDates(dates);

  baseOption.series = [];

  baseOption.series.push({
    name: 'close',
    type: 'line',
    yAxisIndex: 0,
    'data': closes,
    markArea: getMarkAreaDate(dates),
    markPoint: {
      'data': getMarkPoint(data, opShow, sDate),
    },
    markLine: {
      data: [
        { type: 'max', name: 'Max' },
        { type: 'min', name: 'Min' },
        { type: 'average', name: 'Avg' }
      ]
    }
  })

  baseOption.series.push({
    name: '15W',
    type: 'line',
    yAxisIndex: 0,
    data: mean75dCloses
  })

  baseOption.series.push({
    name: '20W',
    type: 'line',
    yAxisIndex: 0,
    data: mean20WCloses
  })

  baseOption.series.push({
    name: '30W',
    type: 'line',
    yAxisIndex: 0,
    data: mean30WCloses
  })

  baseOption.series.push({
    name: '60W',
    type: 'line',
    yAxisIndex: 0,
    data: meanCloses
  })

  baseOption.series.push({
    name: 'level_point',
    type: 'line',
    yAxisIndex: 1,
    data: levelPoints
  })

  return baseOption;
}

export function builtPeAndPbOption(data) {
  setLegendData(["pe_ratio", "pb_ratio"]);

  let dates = []
  let peRatios = []
  let pbRatios = []

  data.forEach(element => {
    dates.push(element.date);
    peRatios.push(element.peRatio);
    pbRatios.push(element.pbRatio);
  });

  setDates(dates);

  baseOption.series = [];
  baseOption.series.push({
    name: 'pe_ratio',
    type: 'line',
    yAxisIndex: 0,
    data: peRatios,
    markArea: getMarkAreaDate(dates),
  })
  baseOption.series.push({
    name: 'pb_ratio',
    type: 'line',
    yAxisIndex: 1,
    data: pbRatios
  })

  return baseOption;
}

export function builtNorthBoundRatio(data) {
  setLegendData(["north_bound_ratio", "close"]);

  let dates = []
  let northBoundRatios = []
  let close = []

  data.forEach(element => {
    dates.push(element.date);
    northBoundRatios.push(element.ratio);
    close.push(element.close);
  });

  setDates(dates);

  baseOption.series = [];
  baseOption.series.push({
    name: 'north_bound_ratio',
    type: 'line',
    yAxisIndex: 0,
    data: northBoundRatios
  })
  baseOption.series.push({
    name: 'close',
    type: 'line',
    yAxisIndex: 1,
    data: close
  })

  return baseOption;
}

/**
 * 两只股票比较
 * @param {*} stocks 
 * @param {*} data 
 */
export function builtTowStockCompare(stocks, data, key) { 

  let stock0 = stocks[0]
  let stock1 = stocks[1]

  setLegendData([stocks[0], stocks[1]]);

  let dates = []
  let v0 = []
  let v1 = []

  let d0 = data[stock0].reverse()
  let d1 = data[stock1].reverse()

  let length = Math.min(d0.length, d1.length)

  d0.slice(-length).forEach(element => {
    dates.push(element.date);
    v0.push(element[key]);
  });
  d1.slice(-length).forEach(element => {
    v1.push(element[key]);
  });

  setDates(dates);

  baseOption.series = [];

  baseOption.series.push({
    name: stock0,
    type: 'line',
    yAxisIndex: 0,
    data: v0,
    markArea: getMarkAreaDate(dates),
  })
  baseOption.series.push({
    name: stock1,
    type: 'line',
    yAxisIndex: 1,
    data: v1
  })
  return baseOption;
}

/**
 * 基金份额
 * @param {*} data 
 * @returns 
 */
export function builtFundUnits(data) {
  setLegendData(["fund_units", "close"]);

  let dates = []
  let fundUnits = []
  let close = []

  data.forEach(element => {
    dates.push(element.date);
    fundUnits.push(element.fundUnits);
    close.push(element.close);
  });

  setDates(dates);

  baseOption.series = [];
  baseOption.series.push({
    name: 'fund_units',
    type: 'line',
    yAxisIndex: 0,
    data: fundUnits,
    markArea: getMarkAreaDate(dates),
  })
  baseOption.series.push({
    name: 'close',
    type: 'line',
    yAxisIndex: 1,
    data: close
  })

  return baseOption;
}

export function builtMarginTradingEchartOption(rawData) { 
  setLegendData(["fin_value", "sec_value"]);

  let dates = []; 
  let finValue = [];
  let secValue = [];

  let reData = new Map();
  rawData.forEach(item => {
    let k = item.date;
    if (reData.has(k)) {
      finValue.push((item.finValue + reData.get(k).finValue) / 1E8)
      secValue.push((item.secValue + reData.get(k).secValue) / 1E8)
    } else {
      dates.push(k)
      reData.set(k, item);
    }
  })

  setDates(dates);

  baseOption.series = [];
  baseOption.series.push({
    name: 'fin_value',
    type: 'line',
    yAxisIndex: 0,
    data: finValue,
    markArea:  getMarkAreaDate(dates)
  })
  baseOption.series.push({
    name: 'sec_value',
    type: 'line',
    yAxisIndex: 1,
    data: secValue,
  })

  return baseOption;
}
